# -*- coding: utf-8 -*-
'''
@author: olivia.dou
Created on: 2022/11/4 16:34
desc:
'''
import logging
from jsonpath import jsonpath
from appium.webdriver.common.touch_action import TouchAction
#from pyautogui import locate
#from PIL import Image
from appium.webdriver.common.appiumby import AppiumBy
import base.globalvars as glo
from proj_spec.CLUE.company_info import retrieve_company
from proj_spec.CLUE.mobile_po.clue_app_base_page import CLUEAppBasePage
from proj_spec.CLUE.mobile_po.surround_region_selection_page import SurroundRegionSelectionPage


class SurroundCustomerPage(CLUEAppBasePage):
    #_choose_region_locator = (AppiumBy.XPATH, "//*[contains(@text,'区域')]") #设置行政区后会变化，需改为唯一标识
    _choose_region_locator = (AppiumBy.XPATH, "//*[@resource-id='around.region']") #区域下拉
    _draw_circle_locator = (AppiumBy.XPATH, "//*[@resource-id='around.draw']") #画图按钮
    _around_list_locator = (AppiumBy.XPATH, "//*[@resource-id='around.list']") #列表按钮
    _swipe_window_locator = (AppiumBy.XPATH, "//*[contains(@text, '共搜索到')]") #拖曳窗口定位
    # mumu上包含拖曳窗口顶部bar,元素索引不同
    # _company_list_locator = (AppiumBy.XPATH, "//*[@resource-id='allmap']/following-sibling::*[1]/child::*[1]/child::*[4]/child::*[1]") #公司列表
    _company_list_locator = (
    AppiumBy.XPATH, "//*[@resource-id='allmap']/following-sibling::*[1]//*[contains(@text,'查看全部')]/../following-sibling::*[1]/child::*[1]")  # 公司列表
    # _last_company_info_locator = (AppiumBy.XPATH, "//*[@resource-id='allmap']/following-sibling::*[1]/child::*[1]/child::*[4]"
    #                                               "/child::*[1]/child::*[last()]//child::*[@text='成立日期']") #列表最后一家公司的信息（可能无标签行）
    _request_location_android = (AppiumBy.ANDROID_UIAUTOMATOR, 'UiSelector().textContains("获取此设备的位置信息")')
    _request_location_android_wework = (AppiumBy.ANDROID_UIAUTOMATOR, 'UiSelector().textContains("访问你当前的地理位置信息")')
    _grant_location_btn_android = (AppiumBy.ANDROID_UIAUTOMATOR, 'UiSelector().text("允许")')
    _grant_location_btn_android_wework = (AppiumBy.ANDROID_UIAUTOMATOR, 'UiSelector().text("允许")')
    _deny_location_btn_android = (AppiumBy.ANDROID_UIAUTOMATOR, 'UiSelector().text("拒绝")')
    _deny_location_btn_android_wework = (AppiumBy.ANDROID_UIAUTOMATOR, 'UiSelector().text("不允许")')
    #Todo: android移动端位置请求相关元素定位


    def open_region_filter(self):
        try:

            self.driver.update_settings({"allowInvisibleElements": True})
            self.find_element_and_click(self._choose_region_locator)
            self.driver.update_settings({"allowInvisibleElements": False})
        except Exception as e:
            logging.error(e)
            raise e

        return SurroundRegionSelectionPage(self.driver)

    def filter_by_region(self, **kwargs):
        #self.find_element_and_click(self._choose_region_locator)

        region_sel_page = self.open_region_filter()
        region_sel_page.choose_region(**kwargs)


    def search_surround_company(self, **kwargs):
        """搜索周边企业

        :param kwargs:
        |distance: 距离选项， 1KM or 2KM or 3KM
        |district: 行政区，e.g."河北省/衡水市/安平县"

        :return:
        """
        webdriver = self.driver # 占位参数
        # def loaded(webdriver):
        #     loading_img = Image.open("loading.png")
        #     loading_black_img = Image.open("loading-black.png") #模拟器性能问题时为黑色区域
        #     if self.driver.save_screenshot("screenshot.png"):
        #         screenshot = Image.open("screenshot.png")
        #         if locate(loading_img, screenshot, confidence=0.9) is None and locate(loading_black_img, screenshot) is None:
        #             return True
        #         else:
        #             return False
        #     else:
        #         return False

        # draw_circle = self.find_element(self._draw_circle_locator)
        # WebDriverWait(self.driver, 20).until(loaded)
        if 'distance' in kwargs or 'district' in kwargs:
            self.filter_by_region(**kwargs)
        # Todo: other filters

    def get_region_selection_text(self, wait_for_update=True):
        """ 获取区域下拉的文本
        :param wait_for_update: 是否等待地图区域刷新

        :return: 区域下拉的文本
        """
        if wait_for_update:
            self.find_element(self._around_list_locator)
        self.driver.update_settings({"allowInvisibleElements": True})
        text = self.find_element(self._choose_region_locator).text
        self.driver.update_settings({"allowInvisibleElements": False})
        return text


    def show_company_list(self):
        """筛选公司后，打开地图上的公司列表

        :return:
        """
        self.find_element_and_click(self._around_list_locator)


    def swipe_company_list_window(self):
        """拖曳公司列表窗口至完整显示

        :return:
        """
        swipe_window = self.find_element(self._swipe_window_locator)
        touch_action = TouchAction(self.driver)
        touch_action.press(swipe_window).perform()
        touch_action.move_to(self.find_element(self._choose_region_locator)).release().perform()


    def is_last_company_info_complete(self):
        """ 判断列表最后一家公司信息完整（兼容性测试）
        页面定位最后一家公司的名称，通过接口调用获取相应产品列表，若产品列表为空，则预期最后一行为“法定代表人"所在行，否则为产品列表所在行
        （使用周边获客接口调用的问题：通过driver.location获取的经纬度与APP实际请求时发送的经纬度有差异，造成列表不一致）

        :return:
        """

        self.swipe_up(self._company_list_locator, 4)
        last_company_info_locator = (AppiumBy.XPATH,
                                      "//*[@resource-id='allmap']/following-sibling::*[1]//*[contains(@text,'查看全部')]/../following-sibling::*[1]"
                                      "/child::*[1]/child::*[last()]")  # 列表最后一家公司
        last_company_element = self.find_element(last_company_info_locator)
        try:
            last_company_element.find_element(AppiumBy.XPATH, '/child::*/child::*')
        except Exception:#为最后的bar，非公司信息
            last_company_info_locator = (AppiumBy.XPATH,
                                      "//*[@resource-id='allmap']/following-sibling::*[1]//*[contains(@text,'查看全部')]/../following-sibling::*[1]"
                                      "/child::*[1]/child::*[last()]/preceding-sibling::*[last()]")
            last_company_element = self.find_element(last_company_info_locator)
        last_company_name = last_company_element.find_element(AppiumBy.XPATH, "/child::*/child::*[3]/child::*[1]").text #从元素查找，第一层子节点是元素自身？
        # location = self.driver.location
        #
        # nearby_customers = get_nearby_customers(location,size=size)
        # size = 20
        # last_company_products = jsonpath(nearby_customers, "$.list[%s].products"%(size-1))
        # last_company_name = jsonpath(nearby_customers, "$.list[%s].stdName"%(size-1))[0]
        # # mumu浏览器公司列表的最后一项是空白bar,因此不能用last()索引
        # last_company_info_locator = (AppiumBy.XPATH, "//*[@resource-id='allmap']/following-sibling::*[1]//*[contains(@text,'查看全部')]"
        #                                              "/../following-sibling::*[1]/child::*[1]//*[@text='%s']/../.."%last_company_name)
        company_data = retrieve_company(keyword=last_company_name)
        last_company_products = jsonpath(company_data, "$.list[*].products")[0]
        if last_company_products==[]:#无产品标签
            last_row = self.find_element(last_company_info_locator).find_element(AppiumBy.XPATH, "/child::*/child::*[4]/child::*[@text='法定代表人']")
        else:
            last_row = self.find_element(last_company_info_locator).find_element(AppiumBy.XPATH, "/child::*/child::*[5]")
        if last_row:
            return True
        else:
            return False

    def handle_location_request(self, grant_location=True):
        """若弹出地理位置授权框，则处理授权
        :param grant_location: 是否授权使用用户当前地理位置， 默认True

        :return:
        """
        # noReset为True的时候，autoGrantPermissions设为True不起作用
        # 企业微信端即使指定autoGrantPermissions为True,也会弹窗授权请求
        if ('noReset' in self.driver.capabilities and self.driver.capabilities['noReset'] is True) or \
                ('autoGrantPermissions' in self.driver.capabilities and self.driver.capabilities['autoGrantPermissions'] is False) \
                or 'wework' in glo.get_value("config_name"):
            request_location_locator_name = '_request_location_' + self.os
            grant_btn_locator_name = '_grant_location_btn_' + self.os
            deny_btn_locator_name = '_grant_location_btn_' + self.os
            if 'wework' in glo.get_value("config_name"):
                request_location_locator_name += "_wework"
                grant_btn_locator_name += "_wework"

            try:
                if self.find_element(getattr(self, request_location_locator_name), timeout=2):
                    if grant_location:
                        self.find_element_and_click(getattr(self, grant_btn_locator_name))
                    else:
                        self.find_element_and_click(getattr(self, deny_btn_locator_name))
            except Exception as e: #没有授权地理位置弹框，正常执行
                pass



